package wiki.generic.concretemed;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import wiki.generic.contents.Content;
import wiki.generic.contents.ContentsPrototypeFactory;
import wiki.generic.io.ContentsReader;
import wiki.generic.io.ContentsWriter;
import wiki.generic.io.GenericDataWriter;
import wiki.generic.io.MapDataReader;
import wiki.generic.io.Page;
import wiki.generic.io.PagesMapReader;
import wiki.generic.managers.PagesMapManager;
import wiki.generic.med.PagesService;
import wiki.generic.utilities.AlreadyExistingElementException;
import wiki.generic.utilities.PageNotFoundException;
/**
 * 
 * @author <p><strong>JwTeam</strong></p> 
 *
 */
public class PageServiceMediator implements PagesService{

	private PagesMapReader pageMap;
	private GenericDataWriter pageMapWriter;
	private ContentsReader creader;
	private ContentsPrototypeFactory pfactory;
	private ContentsWriter cwriter;
	private MapDataReader coursesReader;
	
	

	public PageServiceMediator(PagesMapReader pageMap,
			GenericDataWriter pageMapWriter, ContentsWriter cwriter,
			MapDataReader coursesReader) {
		super();
		this.pageMap = pageMap;
		this.pageMapWriter = pageMapWriter;
		this.cwriter = cwriter;
		this.coursesReader = coursesReader;
		PagesMapManager.getPmanager().setPagesMap(pageMap.getPageMap(coursesReader.getMap()));
	}


	public void createNewPage(String corso,String id, String path)
			throws AlreadyExistingElementException {
		System.out.println(id);
		PagesMapManager.getPmanager().getPagesMap().get(corso).addPage(id,coursesReader.getMap().get(corso)+"/"+path);
		pageMapWriter.saveDataMap(PagesMapManager.getPmanager().getPagesMap().get(corso).getPagesMap(),
				coursesReader.getMap().get(corso)+"/"+pageMap.getFile());
		cwriter.writeContents(new ArrayList<Content>(), coursesReader.getMap().get(corso)+"/"+path);
	}
		

	public HashMap<String, String> getPagesMap(String corso){
		return PagesMapManager.getPmanager().getPagesMap().get(corso).getPagesMap();
	}
	
	public Content getContentbyName(String corso, String current, String name) throws PageNotFoundException{
		List<Content> conts=getCurrentPageContents(corso, current);
		for (int i = 0; i < conts.size(); i++) {
			if(conts.get(i).getContentName().compareTo(name)==0){
				return conts.get(i);
			}
		}
		return null;
	}

	public List<Content> getCurrentPageContents(String corso,String id)
			throws PageNotFoundException {
		String filePath = PagesMapManager.getPmanager().getPagesMap().get(corso).getValueById(id);
		Page p = creader.getPage(filePath);
		return p.getContentsList();
	}
	public Content generateContent(String nome, String type,
			int ID, List<String> attributes) {
		return pfactory.generateContent(nome, type, ID, attributes);
	}
	
	@Override
	public void setPFactory(ContentsPrototypeFactory pfactory) {
		this.pfactory=pfactory;
	}
	public void setCreader(ContentsReader creader) {
		this.creader = creader;
	}
}
